package com.nnnu.wsnackshop.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nnnu.wsnackshop.constant.MessageConstants;
import com.nnnu.wsnackshop.constant.StatusCodeConstants;
import com.nnnu.wsnackshop.controller.base.BaseController;
import com.nnnu.wsnackshop.mapper.MemberPointsMapper;
import com.nnnu.wsnackshop.mapper.MembersMapper;
import com.nnnu.wsnackshop.pojo.entity.MemberPoints;
import com.nnnu.wsnackshop.pojo.entity.Members;
import com.nnnu.wsnackshop.pojo.entity.Users;
import com.nnnu.wsnackshop.result.PageResult;
import com.nnnu.wsnackshop.result.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * <p>
 * 用户积分相关 前端控制器
 * </p>
 *
 * @author ai-assistant
 * @since 2025-06-26
 */
@RestController("userPointsController")
@RequestMapping("/api/user/points")
@Tag(name = "用户积分接口", description = "用户积分相关的API")
@RequiredArgsConstructor
@Slf4j
@RequiresRoles(value = { "user" }, logical = Logical.OR)
public class PointsController extends BaseController {

    private final MemberPointsMapper memberPointsMapper;
    private final MembersMapper membersMapper;

    /**
     * 获取积分历史记录
     */
    @Operation(summary = "获取积分历史记录", description = "分页获取当前用户的积分变动记录")
    @GetMapping("/history")
    public Result<PageResult<MemberPoints>> getPointsHistory(
            @Parameter(description = "页码，从1开始") @RequestParam(defaultValue = "1") Integer page,
            @Parameter(description = "每页记录数") @RequestParam(defaultValue = "10") Integer pageSize) {

        if (!isLogin()) {
            return Result.error(StatusCodeConstants.UNAUTHORIZED, MessageConstants.NOT_LOGIN);
        }

        Integer userId = getUserId();
        log.info("获取用户积分历史: userId={}, page={}, pageSize={}", userId, page, pageSize);

        try {
            // 先根据userId查询会员ID
            LambdaQueryWrapper<Members> memberQuery = new LambdaQueryWrapper<>();
            memberQuery.eq(Members::getUserId, userId);
            Members member = membersMapper.selectOne(memberQuery);

            if (member == null) {
                log.warn("未找到会员信息: userId={}", userId);
                return Result.success(new PageResult<>(0L, null), "未找到会员信息");
            }

            // 查询积分历史记录
            Page<MemberPoints> pageParam = new Page<>(page, pageSize);
            LambdaQueryWrapper<MemberPoints> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(MemberPoints::getMemberId, member.getId())
                    .orderByDesc(MemberPoints::getCreatedAt);

            Page<MemberPoints> resultPage = memberPointsMapper.selectPage(pageParam, queryWrapper);

            // 返回分页结果
            return Result.success(
                    new PageResult<>(resultPage.getTotal(), resultPage.getRecords()),
                    "获取积分历史成功");
        } catch (Exception e) {
            log.error("获取积分历史异常: userId={}, error={}", userId, e.getMessage(), e);
            return Result.error(StatusCodeConstants.INTERNAL_SERVER_ERROR, "获取积分历史失败：" + e.getMessage());
        }
    }

    /**
     * 获取积分汇总信息
     */
    @Operation(summary = "获取积分汇总信息", description = "获取当前用户的积分汇总信息，包括总积分、成长值和会员等级")
    @GetMapping
    public Result<Map<String, Object>> getUserPoints() {
        if (!isLogin()) {
            return Result.error(StatusCodeConstants.UNAUTHORIZED, MessageConstants.NOT_LOGIN);
        }

        Integer userId = getUserId();
        log.info("获取用户积分汇总: userId={}", userId);

        try {
            // 查询会员信息
            LambdaQueryWrapper<Members> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Members::getUserId, userId);
            Members member = membersMapper.selectOne(queryWrapper);

            if (member == null) {
                return Result.error(StatusCodeConstants.NOT_FOUND, "未找到会员信息");
            }

            // 返回积分信息
            Map<String, Object> pointsInfo = Map.of(
                    "points", member.getPoints() != null ? member.getPoints() : 0,
                    "growthValue", member.getGrowthValue() != null ? member.getGrowthValue() : 0,
                    "memberLevel", member.getMemberLevelId() != null ? member.getMemberLevelId() : 1);

            return Result.success(pointsInfo, "获取积分信息成功");
        } catch (Exception e) {
            log.error("获取积分信息异常: userId={}, error={}", userId, e.getMessage(), e);
            return Result.error(StatusCodeConstants.INTERNAL_SERVER_ERROR, "获取积分信息失败：" + e.getMessage());
        }
    }
}